package com.atung.parking.config.tlPay;


import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 */
public class HttpUrlConnectionUtil {
    protected String url;
    protected Map<String, String> heads = new HashMap<>();
    protected Integer connectTimeout = 3000;
    protected Integer readTimeout = 3000;
    protected RequestParamTypeEnum paramType = RequestParamTypeEnum.JSON;
    protected String body;
    protected RequestMethod method;

    public HttpUrlConnectionUtil setBody(String paramBody) {
        this.body = paramBody;
        return this;
    }

    /**
     * @param paramUrl
     */
    public HttpUrlConnectionUtil setUrl(String paramUrl) {
        this.url = paramUrl;
        return this;
    }

    public HttpUrlConnectionUtil setMethod(RequestMethod method) {
        this.method = method;
        return this;
    }

    public HttpUrlConnectionUtil setParamType(RequestParamTypeEnum requestParamTypeEnum) {

        paramType = requestParamTypeEnum;
        return this;
    }

    /**
     * 设置请求头
     *
     * @param paramHeads
     */
    public HttpUrlConnectionUtil setHeads(Map<String, String> paramHeads) {
        if (Objects.nonNull(paramHeads)) {
            this.heads.putAll(paramHeads);
        }
        return this;
    }

    /**
     * 限制socket等待建立连接的时间，超时将会抛出java.net.SocketTimeoutException
     *
     * @param connectTimeout
     */
    public HttpUrlConnectionUtil setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
        return this;
    }

    /**
     * 限制输入流等待数据到达的时间，超时将会抛出java.net.SocketTimeoutException
     *
     * @param readTimeout
     */
    public HttpUrlConnectionUtil setReadTimeout(Integer readTimeout) {
        this.readTimeout = readTimeout;
        return this;
    }


    public static HttpUrlConnectionUtil post() {
        HttpUrlConnectionUtil httpUrlConnectionUtil = new HttpUrlConnectionUtil();
        httpUrlConnectionUtil.setMethod(RequestMethod.POST);
        return httpUrlConnectionUtil;
    }

    public static HttpUrlConnectionUtil get() {
        HttpUrlConnectionUtil httpUrlConnectionUtil = new HttpUrlConnectionUtil();
        httpUrlConnectionUtil.setMethod(RequestMethod.GET);
        return httpUrlConnectionUtil;
    }

    public String connection() {
        HttpURLConnection connection = null;
        OutputStreamWriter outputStreamWriter = null;
        BufferedInputStream bufferedInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        if (!StringUtils.hasText(url)) {
            return null;
        }
        try {
            URL url = new URL(this.url);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(this.connectTimeout);
            // 限制输入流等待数据到达的时间，超时将会抛出java.net.SocketTimeoutException
            connection.setReadTimeout(this.readTimeout);
            //设置请求方式
            connection.setRequestMethod(this.method.name());
            //设置请求头
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                connection.setRequestProperty(key, value);
            }

            //请求参数类型
            connection.setRequestProperty("Content-Type", this.paramType.getTypeValue());
            connection.setRequestProperty("Accept", "application/json;charset=utf-8");
            // 设置是否从httpUrlConnection读入，默认情况下是true
            connection.setDoInput(true);
            // 由于URLConnection在默认的情况下不允许输出，所以在请求输出流之前必须调用setDoOutput(true)。为一个HTTP URL将doOutput设置为true时，请求方法将由GET变为POST
            connection.setDoOutput(true);
            // 是否使用缓存，Post方式不能使用缓存
            connection.setUseCaches(false);

            if (StringUtils.hasText(this.body)) {
                outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
                outputStreamWriter.write(this.body);
                outputStreamWriter.close();
            }
            if (connection.getResponseCode() == 200) {
                bufferedInputStream = new BufferedInputStream(connection.getInputStream());
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];
                int len = 0;
                if ((len = bufferedInputStream.read(buff)) != -1) {
                    byteArrayOutputStream.write(buff, 0, len);
                }
                return byteArrayOutputStream.toString();

            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }
}
